/*
 * @Author: liangliang
 * @Date: 2023-05-18 15:40:29
 * @LastEditors: yusha
 * @LastEditTime: 2023-08-25 10:14:43
 * @Description: OEM供应商列表
 */

import React, { useState } from 'react';
import { useAntdTable } from 'ahooks';
import { Button, Form, Input, Row, message, Space, DatePicker, Table, Modal, Tooltip, Select, Col } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { OemSupplier } from '@/service/order';
import { useFormModal } from '@/hooks/useFormModal';
import { request } from '@/config/request';
import EditSupplierInfo from './module/EditSupplierInfo';
import './index.scss';

interface OemSupplierProps extends OemSupplier{
  key?: number;
}

const SupplierList: React.FC = () => {
    const [form] = Form.useForm();
    const formModalSupplierInfo = useFormModal();
    const formModalOperationLog = useFormModal();
    const [rowItem, setRowItem] = useState<OemSupplier>();
    const [isEditInfo, setIsEditInfo] = useState(false);

    const { tableProps, search } = useAntdTable(async ({ pageSize, current: pageNum }) => {
        const { oemSupplierId, supplierName, timeStart, supplierType } = form.getFieldsValue();
        const params = {
            oemSupplierId,
            supplierName,
            timeStart: timeStart?.[0]?.format('YYYY-MM-DD 00:00:00'),
            timeEnd: timeStart?.[1]?.format('YYYY-MM-DD 23:59:59'),
            pageNum,
            pageSize,
            supplierType
        };
        const res = await request.order.oem.supplierList(params);
        return {
            total: res.data?.total ?? 0,
            list: res.data?.records ?? []
        };
    }, { defaultPageSize: 10, form });

    const columns: ColumnsType<OemSupplierProps> = [
        {
            title: '序号',
            dataIndex: 'key',
            key: 'key',
            width: 100,
            render: (value, record, index) => <span>{index + 1}</span>
        },
        {
            title: '供应商ID',
            dataIndex: 'oemSupplierId',
            key: 'oemSupplierId',
            width: 100
        },
        {
            title: '供应商名称',
            dataIndex: 'supplierName',
            key: 'supplierName',
            width: 140
        },
        {
            title: '主营类目',
            dataIndex: 'mainCategory',
            key: 'mainCategory',
            width: 160,
            ellipsis: { showTitle: false },
            render: (text) =>
                <Tooltip placement="topLeft" title={text}>
                    {text}
                </Tooltip>
            ,
        },
        {
            title: '是否支持定制',
            dataIndex: 'supportCustomizationFlag',
            key: 'supportCustomizationFlag',
            width: 150,
            render: (text) => <a>{ text === 1 ? '是' : '否'}</a>,
        },
        {
            title: '联系人姓名',
            dataIndex: 'contactPerson',
            key: 'contactPerson',
            width: 150
        },
        {
            title: '手机号',
            dataIndex: 'tel',
            key: 'tel',
            width: 150
        },
        {
            title: '地址',
            dataIndex: 'supplierAddress',
            key: 'supplierAddress',
            width: 100,
            ellipsis: { showTitle: false },
            render: (text) =>
                <Tooltip placement="topLeft" title={text}>
                    {text}
                </Tooltip>
            ,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 100,
        },
        {
            title: '查看1688链接',
            dataIndex: 'alibabaUrl',
            key: 'alibabaUrl',
            width: 130,
            render: (url) =>
                <>
                    {
                        url ?
                            <a href={url} style={{ color: '#1677ff' }}>查看详情</a> :
                            null
                    }
                </>
            ,
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 60,
            render: (_: any, record: any) => {
                return (
                    <Space size="middle" className="flex-col">
                        <Button
                            type="link" size="small"
                            onClick={() => {
                                setRowItem(record);
                                setIsEditInfo(true);
                                formModalSupplierInfo.modal.open();
                            }}
                        >
                          修改
                        </Button>
                    </Space>
                );
            }
        },
    ];

    // 新增/修改供应商信息
    const editSupplierInfo = async() => {
        const params = await formModalSupplierInfo.form.validateFields();
        try {
            const response = isEditInfo ?
                await request.order.oem.supplierUpdate({
                    ...rowItem,
                    ...params,
                }) : await request.order.oem.supplierAdd(params);
            if (response.success) {
                message.success('保存成功！');
                formModalSupplierInfo.modal.close();
                search.submit();
            }
        } catch (error: any) {
            message.error(error);
        }
    };

    return (
        <div className="bg-white p-2.5">
            <Form form={form} name="supplierList_search">
                <Row>
                    <Col span={6}>
                        <Form.Item label="供应商ID" name="oemSupplierId">
                            <Input placeholder="请输入" allowClear />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="供应商名称" name="supplierName">
                            <Input placeholder="请输入" allowClear />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="供应商类型" name="supplierType">
                            <Select
                                placeholder="请选择供应商类型"
                                options={[
                                    { label: '全部', value: '' },
                                    { label: 'OEM供应商', value: 1 },
                                    { label: '成品供应商', value: 2 },
                                ]}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="创建日期" name="timeStart">
                            <DatePicker.RangePicker placeholder={['开始日期', '结束日期']} style={{ width: '100%' }} />
                        </Form.Item>
                    </Col>
                    <Col span={24} style={{ textAlign: 'right' }}>
                        <Form.Item>
                            <Space size="small">
                                <Button type="primary" htmlType="submit" onClick={search.submit}>搜索</Button>
                                <Button type="primary" onClick={search.reset}>重置</Button>
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
                <div style={{ textAlign: 'left', marginBottom: 16 }}>
                    <Button
                        type="primary" className="mt-5 mb-5" onClick={() => {
                            setIsEditInfo(false);
                            setRowItem({});
                            formModalSupplierInfo.modal.open();
                        }}
                    >新增供应商信息</Button>
                </div>

                <Table
                    {...tableProps}
                    bordered
                    columns={columns}
                    rowKey="oemSupplierId"
                    locale={{ emptyText: '暂无数据' }}
                    scroll={{ x: 'calc(100vw + 1000px)' }}
                />
            </Form>
            <Modal
                destroyOnClose
                open={formModalSupplierInfo.isOpen}
                onOk={() => editSupplierInfo()}
                onCancel={() => { formModalSupplierInfo.modal.close(); }}
                title={isEditInfo ? '修改供应商信息' : '新增供应商信息' }
                className="supplierInfoModal" okText="确定" cancelText="取消" maskClosable={false}
            >
                <EditSupplierInfo formModal={formModalSupplierInfo} rowItem={rowItem} />
            </Modal>
        </div>
    );
};

export default SupplierList;
